package com.bto.solar.work.lease;

import com.bto.solar.work.constant.BizStageEnum;
import com.bto.solar.work.constant.BizTaskEnum;
import com.bto.solar.work.constant.BizTaskStateEnum;
import com.bto.solar.work.dao.IOrderBaseService;
import com.bto.solar.work.dto.lease.OperatingStatusQueryRes;
import com.bto.solar.work.dto.lease.YsxxResultRes;
import com.bto.solar.work.entity.OrderBase;
import com.bto.solar.work.entity.OrderState;
import com.bto.solar.work.service.BtoOrderStateService;
import com.bto.solar.work.utils.LogUtils;
import com.bto.solar.work.utils.NullUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
public class LeaseSyncStateService {

    @Autowired
    private BtoOrderStateService btoOrderStateService;
    @Autowired
    private LeaseApi leaseApi;
    @Autowired
    private IOrderBaseService orderBaseService;

    @Scheduled(cron = "0 0/1 * * * ? ")
    @Async
    public void syncYsxxState () {
        LogUtils.syncLeaseStateLogger.info("=======================================预审状态查询定时任务开始===================================================");
        try {
            List<OrderState> orderStateList = btoOrderStateService.getOrderStateList(BizStageEnum.PRE_APPROVAL.getStageId(),
                    BizTaskEnum.TASK_YSXX.getTaskId(), BizTaskStateEnum.WAITING_APPROVAL_LEASE.getStateId());
            if (NullUtils.isNotEmpty(orderStateList)) {
                List<String> orderIdList = orderStateList.stream().map(OrderState::getOrderId).collect(Collectors.toList());
                orderIdList.forEach(orderId -> {
                    OrderBase orderBase = orderBaseService.getById(orderId);
                    if (NullUtils.isNull(orderBase)) {
                        LogUtils.syncLeaseStateLogger.info("这个订单号{}，没有找到无法同步", orderId);
                    } else {
                        YsxxResultRes ysxxResultRes = leaseApi.getTenantPreAuditState(orderBase);
                        if (null != ysxxResultRes && "S".equals(ysxxResultRes.getType())) {
                            OperatingStatusQueryRes res = new OperatingStatusQueryRes();
                            //buinessKey为身份证
                            res.setBusinessKey(ysxxResultRes.getIdCardNo());
                            OperatingStatusQueryRes.PrjProjectOperatingLeaseStatus prjProjectOperatingLeaseStatus = new OperatingStatusQueryRes.PrjProjectOperatingLeaseStatus();
                            //审核结果
                            prjProjectOperatingLeaseStatus.setTenantStatus(ysxxResultRes.getResult());
                            //审核理由
                            prjProjectOperatingLeaseStatus.setReason(ysxxResultRes.getReason());
                            res.setPrjProjectOperatingLeaseStatus(prjProjectOperatingLeaseStatus);
                            leaseApi.syncApprovalLeaseStatusAndLeaseRiew(orderBase, res);
                            LogUtils.syncLeaseStateLogger.info(formatLeaseSyncStateLog(res));
                        } else {
                            LogUtils.syncLeaseStateLogger.info("该订单{}，同步预审核状态接口失败 {} ", orderId , ysxxResultRes.getReason());
                        }
                    }
                });
            }
        } catch (Exception e) {
            LogUtils.syncLeaseStateLogger.info("同步预审核状态任务失败:" + e.getMessage());
        }

        LogUtils.syncLeaseStateLogger.info("=======================================预审状态查询定时任务结束===================================================");

    }


    @Scheduled(cron = "0 0/1 * * * ? ")
    @Async
    public void syncState () {
        LogUtils.syncLeaseStateLogger.info("=======================================开启进件后定时任务===================================================");
        try {
            List<String> orderStateList = btoOrderStateService.getOrderStateByWaitingLeaseList();
            if (NullUtils.isNotEmpty(orderStateList)) {
                Set<String> orderIds = new HashSet<>(orderStateList);
                orderIds.forEach(orderId -> {
                    OrderBase orderBase = orderBaseService.getById(orderId);
                    if (NullUtils.isNull(orderBase)) {
                        LogUtils.syncLeaseStateLogger.info("这个订单号{}，没有找到无法同步", orderId);
                    } else {
                        OperatingStatusQueryRes operatingStatusQueryRes = leaseApi.operatingStatusQuery(orderBase.getOrderId());
                        if (null != operatingStatusQueryRes && "S".equals(operatingStatusQueryRes.getType())) {
                            leaseApi.syncApprovalLeaseStatusAndLeaseRiew(orderBase, operatingStatusQueryRes);
                            LogUtils.syncLeaseStateLogger.info(formatLeaseSyncStateLog(operatingStatusQueryRes));
                        } else {
                            LogUtils.syncLeaseStateLogger.info("该订单{}，同步资方状态接口失败", orderId);
                        }
                    }
                });
            }
        } catch (Exception e) {
            LogUtils.syncLeaseStateLogger.info("同步进件后的状态定时任务失败", e.getMessage());
        }
        LogUtils.syncLeaseStateLogger.info("=======================================结束进件后定时任务===================================================");
    }


    private String formatLeaseSyncStateLog(OperatingStatusQueryRes res){
        StringBuilder builder = new StringBuilder();
        builder.append("订单："+res.getBusinessKey()+"\n");
        builder.append("承租人预审状态（tenantStatus）:" + res.getPrjProjectOperatingLeaseStatus().getTenantStatus()+"\n");
        builder.append("风险审查状态（projectStatus）:" + res.getPrjProjectOperatingLeaseStatus().getProjectStatus()+"\n");
        builder.append("农户投放审查状态（farmerSignStatus）:" + res.getPrjProjectOperatingLeaseStatus().getFarmerSignStatus()+"\n");
        builder.append("投放款付款申请状态（paymentApplyStatus）:" + res.getPrjProjectOperatingLeaseStatus().getPaymentApplyStatus()+"\n");
        builder.append("投放款支付状态（paymentStatus）:" + res.getPrjProjectOperatingLeaseStatus().getPaymentStatus()+"\n");
        builder.append("合同状态（contractStatus）:" + res.getPrjProjectOperatingLeaseStatus().getContractStatus()+"\n");
        builder.append("合同文本状态（农户）（contractTextStatus）:" + res.getPrjProjectOperatingLeaseStatus().getContractTextStatus()+"\n");
        builder.append("租后购售电合同补充状态（contractPowerStatus）:" + res.getPrjProjectOperatingLeaseStatus().getTenantStatus()+"\n");

        return builder.toString();
    }
}
